package xyf.p01.array_nodelist;

import commons.ListNode;

/**
 * ClassName: P0025_KReverse
 * Description:
 * Author: xyf
 * Date: 9/7/22 7:43 PM
 * Version: 1.0
 **/
public class P0025_KReverse
{
    public ListNode reverseKGroup(ListNode head, int k)
    {
        ListNode dummyHead = new ListNode();
        dummyHead.next = head;

        ListNode pre = dummyHead;
        ListNode start = pre.next;
        ListNode cur = pre.next;
        ListNode next = null;
        int curSum = 1;
        while (cur != null)
        {
            next = cur.next;
            if (curSum == k)
            {
                cur.next = null;
                ListNode reverse = reverse(start);
                pre.next = reverse;
                pre = start;
                start = next;
                curSum = 0;
            }
            curSum++;
            cur = next;
        }

        if (curSum > 1)
        {
            pre.next = start;
        }

        return dummyHead.next;
    }

    private ListNode reverse(ListNode head)
    {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null)
        {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}
